import {computed, onUnmounted, ref } from "vue";

export default function UserLoginForm(emits) {
    const loginTab = ref('password')
    const changeLoginType = () => {
        loginTab.value = loginTab.value === 'password' ? 'code' : 'password'
    }

    /**
     * 倒计时相关
     * @type {Ref<UnwrapRef<{timer: null, count: number}>>}
     */
    // 倒计时
    const codeMap = ref({
        timer: null,
        count: 0
    })
    const codeButtonText = computed(() => {
        return codeMap.value.count > 0 ? `${codeMap.value.count}秒后重新获取` : '获取验证码'
    })
    // 获取验证码 60s倒计时 type: login | register
    const handleGetCode = (type = 'login') => {
        if (codeMap.value.count > 0) return
        codeMap.value.count = 60
        codeMap.value.timer = setInterval(() => {
            codeMap.value.count--
            if (codeMap.value.count <= 0) {
                clearInterval(codeMap.value.timer)
                codeMap.value.timer = null
                codeMap.value.count = 0
            }
        }, 1000)
    }


    // 跳转注册 type: login | register
    const loginChange = (type = 'login') => {
        console.log('emits',emits)
        emits('changeLoginType', type)
    }
    // 卸载时清除定时器
    onUnmounted(() => {
        clearInterval(codeMap.value.timer)
    })
    return {
        loginTab,
        changeLoginType,
        codeMap,
        codeButtonText,
        handleGetCode,
        loginChange
    }
}